﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <title></title>
    <link href="/css/mui.min.css" rel="stylesheet" />
    <script src="/Script/torem.js"></script>
    <script src="/Script/mui.min.js"></script>
    <style>
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        body {
            background-color: #f5f5f5;
            padding: .57rem .12rem .12rem .12rem;
            height: 100vh;
            width: 100vw;
            overflow-y: scroll;
        }

        .month-box {
            display: grid;
            height: .6rem;
            grid-template-columns: repeat(2,1fr);
            grid-column-gap: .2rem;
        }

            .month-box > div {
                background-color: #f5f5f5;
                font-size: .14rem;
                border-radius: .12rem;
                display: flex;
                justify-content: center;
                align-items: center;
            }

            .month-box > .active {
                background-color: #007aff;
                color: #fff;
            }

        .time-box {
            display: grid;
            grid-template-columns: repeat(3,1fr);
            grid-column-gap: .14rem;
            margin-top: .16rem;
        }

            .time-box > div {
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: .14rem;
                border: 1px solid #E5E5E5;
                border-radius: .12rem;
                padding: .14rem;
                position: relative;
            }

                .time-box > div > img {
                    position: absolute;
                    width: .2rem;
                    height: .2rem;
                    top: .06rem;
                    right: .06rem;
                }

                .time-box > div > div {
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                    font-size: .12rem;
                }

                    .time-box > div > div > img {
                        width: .2rem;
                        height: .2rem;
                        margin-bottom: .06rem;
                    }

        .title {
            font-size: .14rem;
            height: .4rem;
            line-height: .4rem;
        }

        .moneyInfo {
            background-color: #fff;
            border-radius: .12rem;
        }

            .moneyInfo > div {
                display: flex;
                justify-content: space-between;
                align-items: center;
                font-size: .14rem;
                height: .4rem;
                padding: 0 .14rem;
            }

        .text-primary {
            color: #007aff;
        }

        .cell {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 .14rem;
            font-size: .14rem;
            height: .45rem;
            background-color: #fff;
            border-radius: .12rem;
        }

            .cell img {
                width: .2rem;
                height: .2rem;
            }

        .card {
            font-size: .14rem;
            background-color: #fff;
            border-radius: .12rem;
            padding: .12rem;
            margin-bottom: .16rem;
        }

        .btn {
            width: 100%;
            height: .4rem;
            background-color: #007aff;
            text-align: center;
            line-height: .4rem;
            border-radius: .12rem;
            color: #fff;
        }

        .label {
            color: #8c8c8c;
        }

        #calendar, #calendar1 {
            display: grid;
            grid-template-columns: re
        }

            #calendar > div, #calendar1 > div {
                display: grid;
                grid-template-columns: repeat(7,1fr);
                height: .4rem;
            }

                #calendar > div > div, #calendar1 > div > div {
                    flex-grow: 1;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }

        .date-item-disabled {
            color: #ccc;
        }

        .date-item-active {
            background-color: #007aff;
            color: #fff;
            border-radius: .04rem;
        }

        /* HTML: <div class="loader"></div> */
        .loader {
            width: 30px;
            padding: 4px;
            aspect-ratio: 1;
            border-radius: 50%;
            background: #ccc;
            --_m: conic-gradient(#0000 10%,#000), linear-gradient(#000 0 0) content-box;
            -webkit-mask: var(--_m);
            mask: var(--_m);
            -webkit-mask-composite: source-out;
            mask-composite: subtract;
            animation: l3 1s infinite linear;
        }

        @keyframes l3 {
            to {
                transform: rotate(1turn)
            }
        }

        .mask {
            position: absolute;
            top: 0;
            left: 0;
            background: rgba(0,0,0,0.5);
            width: 100vw;
            height: 100vh;
        }

            .mask > div {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%,-50%);
                background: #fff;
                border-radius: .12rem;
                padding: .12rem;
                display: flex;
                justify-content: center;
                align-items: center;
                width: 50%;
                min-height: .8rem;
            }

        .date-item-notDisabled1 {
            color: #007aff;
        }

        .sub2 {
            font-size: .1rem;
            color: #6B7280;
        }

        .mt-6 {
            margin-top: .02rem;
        }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: fixed;
            top: 0;
            left: 0;
            height: .45rem;
            width: 100vw;
            background-color: #fff;
            z-index: 9999;
            padding: 0 .12rem;
        }

            header > img {
                width: .2rem;
                height: .2rem;
            }

        .success {
            display: none;
            font-size: .14rem;
            padding-top: .5rem;
            text-align: center;
            margin-bottom: .5rem;
        }

        #thisMonth, #nextMonth {
            display: none;
        }
    </style>
</head>
<body>
    <header>
        <img src="/images/left.png" alt="" onclick="history.go(-1)" />
        <span>餐费预定</span>
        <span></span>
    </header>
    <div class="card" id="thisMonth">
        <div style="font-size:.16rem;">本月补订</div>
        <div class="time label" style="font-size:.12rem;margin-top:.06rem;"><span id="nowMonthLanel"></span> 共<span id="nowMonthLength"></span>天</div>
        <div class="time-box">
            <div class="time-item nowtimespan" data-time="breakfast">
                <div class="time-item-info">
                    <img src="/images/orderFood/a.svg" />
                    <span>早餐</span>
                    <span class="breakfast-amount sub2 mt-6"></span>
                </div>
                <img src="/images/orderFood/d.svg" class="icon" />
            </div>
            <div class="time-item nowtimespan" data-time="lunch">
                <div class="time-item-info">
                    <img src="/images/orderFood/b.svg" />
                    <span>中餐</span>
                    <span class="lunch-amount sub2 mt-6"></span>
                </div>
                <img src="/images/orderFood/d.svg" class="icon" />
            </div>
            <div class="time-item nowtimespan" data-time="dinner">
                <div class="time-item-info">
                    <img src="/images/orderFood/c.svg" />
                    <span>晚餐</span>
                    <span class="dinner-amount sub2 mt-6"></span>
                </div>
                <img src="/images/orderFood/d.svg" class="icon" />
            </div>

        </div>
        <div style="margin-top:.1rem;">本月订餐日期</div>
        <div id="calendar"></div>
        <div style="margin: .16rem 0 .16rem 0;"><span>总计金额：￥</span><span style="font-size:.18rem;" id="nowMoney">360.00</span></div>
        <div class="btn" onclick="submitOfNowmonth()">立即补订</div>
    </div>
    <div class="card" id="nextMonth">
        <div style="font-size:.16rem;">下月预定</div>
        <div class="time label" style="font-size:.12rem;margin-top:.06rem;"><span id="nextMonthLanel"></span> 共 <span id="afterMonthLength"></span>天</div>
        <div class="time-box">
            <div class="time-item nexttimespan" data-time="breakfast">
                <div class="time-item-info">
                    <img src="/images/orderFood/a.svg" />
                    <span>早餐</span>
                    <span class="breakfast-amount sub2 mt-6"></span>
                </div>
                <img src="/images/orderFood/d.svg" class="icon" />
            </div>
            <div class="time-item nexttimespan" data-time="lunch">
                <div class="time-item-info">
                    <img src="/images/orderFood/b.svg" />
                    <span>中餐</span>
                    <span class="lunch-amount sub2 mt-6"></span>
                </div>
                <img src="/images/orderFood/d.svg" class="icon" />
            </div>
            <div class="time-item nexttimespan" data-time="dinner">
                <div class="time-item-info">
                    <img src="/images/orderFood/c.svg" />
                    <span>晚餐</span>
                    <span class="dinner-amount sub2 mt-6"></span>
                </div>
                <img src="/images/orderFood/d.svg" class="icon" />
            </div>
        </div>
        <div style="margin-top:.1rem;">下月订餐日期</div>
        <div id="calendar1"></div>
        <div style="margin: .16rem 0 .16rem 0;"><span>总计金额：￥</span><span style="font-size:.18rem;" id="afterMoney">360.00</span></div>
        <div class="btn" onclick="submitOfNextmonth()">立即预定</div>
    </div>



    <div class="moneyInfo">
        <div class="title">餐费说明</div>
        <div class="label" id="breakfast">早餐：￥2.9/餐</div>
        <div class="label" id="lunch">中餐：￥9/餐</div>
        <div class="label" id="dinner">晚餐：￥9/餐</div>
        <div class="label">补订将自动计算补订开始时间至剩余天数</div>
    </div>
    <div class="success">
        下月餐费预订完成
    </div>
    <div class="cell" style="margin-top:.16rem;" onclick="location.href='./orderList.html'">
        <span>预定记录</span>
        <img src="/images/orderFood/right.svg" alt="Alternate Text" />
    </div>

    <script src="/Scripts/jquery-2.1.1.min.js"></script>
    <script>
        var orderDate = [], nextOrderDate = [];
        const timeMoney = {
            breakfast: 2,
            lunch: 10,
            dinner: 12
        }
        var userAmount = 0 //用户余额
        const selData = {
            now: {
                timespan: new Set(["breakfast", "lunch", "dinner"]),
                days: 0,
                money: 0,
                month: new Date().getMonth() + 1,
                selDateList: []
            },
            after: {
                timespan: new Set(["breakfast", "lunch", "dinner"]),
                days: nextOrderDate.length,
                money: 0,
                month: new Date().getMonth() + 2
            }
        }
        function generateCalendar(year, month) {
            const firstDay = new Date(year, month - 1, 1);
            const totalDays = new Date(year, month, 0).getDate();
            const startDay = (firstDay.getDay() + 6) % 7;
            const days = [];
            for (let i = 0; i < startDay; i++) days.push('');
            for (let i = 1; i <= totalDays; i++) days.push(i);
            const weeks = [];
            while (days.length > 0) {
                const week = days.splice(0, 7);
                while (week.length < 7) week.push('');
                weeks.push(week);
            }

            return {
                weekHeaders: ['一', '二', '三', '四', '五', '六', '日'],
                weeks
            };
        }

        function renderCalendar() {
            const calendar = generateCalendar(new Date().getFullYear(), new Date().getMonth() + 1); // 2023年10月
            const container = document.getElementById('calendar');

            // 渲染星期标题
            const header = document.createElement('div');
            calendar.weekHeaders.forEach(text => {
                const cell = document.createElement('div');
                cell.textContent = text;

                header.appendChild(cell);
            });
            container.appendChild(header);

            // 渲染日期内容
            calendar.weeks.forEach(week => {
                const weekDiv = document.createElement('div');
                weekDiv.className = "date-row"
                week.forEach(day => {
                    const cell = document.createElement('div');
                    cell.className = "date-item"
                    if (orderDate.findIndex(v => Number(v.split("-")[2]) == day) == -1) {
                        cell.className = "date-item-disabled"

                    } else {
                        cell.dataset.time = orderDate.find(v => Number(v.split("-")[2]) == day)
                        cell.className = new Date() < new Date(cell.dataset.time) ? "date-item-notDisabled" : "date-item-disabled"
                    }
                    cell.id = `date-item-${day}`
                    cell.textContent = day || '';
                    weekDiv.appendChild(cell);
                });
                container.appendChild(weekDiv);
            });
            $(".date-item-notDisabled")

            selData.now.selDateList = Array.from($(".date-item-notDisabled")).map(v => v.dataset.time)
        }
        function renderNextCalendar() {
            const calendar = generateCalendar(new Date().getFullYear(), new Date().getMonth() + 2); // 2023年10月
            const container = document.getElementById('calendar1');
            const header = document.createElement('div');
            calendar.weekHeaders.forEach(text => {
                const cell = document.createElement('div');
                cell.textContent = text;

                header.appendChild(cell);
            });
            container.appendChild(header);
            calendar.weeks.forEach(week => {
                const weekDiv = document.createElement('div');
                weekDiv.className = "date-row"
                week.forEach(day => {
                    const cell = document.createElement('div');
                    cell.className = "date-item"
                    if (nextOrderDate.findIndex(v => Number(v.split("-")[2]) == day) == -1) {
                        cell.className = "date-item-disabled"

                    } else {
                        cell.dataset.time = nextOrderDate.find(v => Number(v.split("-")[2]) == day)
                        cell.className = new Date() < new Date(cell.dataset.time) ? "date-item-notDisabled1" : "date-item-disabled"
                    }
                    cell.id = `date-item-${day}`
                    cell.textContent = day || '';
                    weekDiv.appendChild(cell);
                });
                container.appendChild(weekDiv);
            });
            //$(".date-item-notDisabled")

            //selData.now.selDateList = Array.from($(".date-item-notDisabled")).map(v => v.dataset.time)
        }



        //$(".nowtimespan").click(function (e) {
        //    const time = e.currentTarget.dataset.time
        //    if (selData.now.timespan.has(time)) {
        //        selData.now.timespan.delete(time)
        //        $(this).find(".icon").first().hide()
        //    } else {
        //        selData.now.timespan.add(time)
        //        $(this).find(".icon").first().show()
        //    }
        //    selData.now.money = [...selData.now.timespan].reduce((acc, cur) => {
        //        const cents = Math.round(timeMoney[cur] * 100);
        //        const days = Math.round(selData.now.days * 100);
        //        return acc + (cents * days) / 10000
        //    }, 0)
        //    selData.now.money = Math.round(selData.now.money * 100) / 100
        //    $("#nowMoney").text(selData.now.money)
        //})
        //$(".nexttimespan").click(function (e) {
        //    const time = e.currentTarget.dataset.time
        //    if (selData.after.timespan.has(time)) {
        //        selData.after.timespan.delete(time)
        //        $(this).find(".icon").first().hide()
        //    } else {
        //        selData.after.timespan.add(time)
        //        $(this).find(".icon").first().show()
        //    }
        //    selData.after.money = [...selData.after.timespan].reduce((acc, cur) => {
        //        const cents = Math.round(timeMoney[cur] * 100);
        //        const days = Math.round(selData.after.days * 100);
        //        return acc + (cents * days) / 10000
        //    }, 0)
        //    selData.after.money = Math.round(selData.after.money * 100) / 100
        //    $("#afterMoney").text(selData.after.money)
        //})
        //补订
        function submitOfNowmonth() {
            mui.confirm(`确认补订${selData.now.month}月份餐费吗`, "提示", ["取消", "确认"], function (e) {
                if (e.index === 1) {
                    if (userAmount < selData.now.money) {
                        mui.confirm(`账户余额不足，还差${selData.now.money - userAmount}元，请及时充值`, "提示", ["确认"], function (e) {

                        })

                        return;
                    }
                    const orderList = []
                    selData.now.selDateList.forEach(v => {
                        selData.now.timespan.forEach(v1 => {
                            orderList.push({
                                date: v,
                                foodTime: v1,
                                money: timeMoney[v1]
                            })
                        })
                    })

                    const data = {
                        amount: selData.now.money,
                        orderList: JSON.stringify(orderList)
                    }
                    submit(data)
                }
            })
        }
        //预定
        function submitOfNextmonth() {
            mui.confirm(`确认预订${selData.after.month}月份餐费吗`, "提示", ["取消", "确认"], function (e) {
                if (e.index === 1) {
                    if (userAmount < selData.after.money) {
                        mui.confirm(`账户余额不足，还差${(selData.after.money * 100 - userAmount * 100 )/100}元，请及时充值`, "提示", ["确认"], function (e) {

                        })

                        return;
                    }
                    const orderList = []
                    nextOrderDate.forEach(v => {
                        selData.after.timespan.forEach(v1 => {
                            orderList.push({
                                date: v,
                                foodTime: v1,
                                money: timeMoney[v1]
                            })
                        })
                    })
                    const data = {
                        amount: selData.after.money,
                        orderList: JSON.stringify(orderList)
                    }
                    submit(data)
                }
            })
        }
        function showMask() {
            document.body.style.position = 'fixed';
            const maskDiv = document.createElement('div');
            maskDiv.classList.add('mask');
            const innerDiv = document.createElement('div');
            const loaderDiv = document.createElement('div');
            loaderDiv.classList.add('loader');
            const textDiv = document.createElement('div');
            textDiv.style.paddingLeft = '0.04rem';
            textDiv.textContent = '支付结果确认中';
            innerDiv.appendChild(loaderDiv);
            innerDiv.appendChild(textDiv);
            maskDiv.appendChild(innerDiv);
            document.body.appendChild(maskDiv);
            maskDiv.style.display = 'block';
            window.maskElement = maskDiv;
        }


        function hideMask() {
            const maskDiv = window.maskElement;
            if (maskDiv) {
                document.body.removeChild(maskDiv);
                document.body.style.position = '';
                window.maskElement = null;
            }
        }

        function getSetting() {
            $.post("/OrderMealManageSubSystem/OrderParameterSetting.ashx", {
                functionName: "GetOrderParameterSetting"
            }).then(res => {
                const result = JSON.parse(JSON.parse(res).data)
                if (result.klb == "走读生") {
                    selData.now.timespan = new Set(["lunch"]);
                    selData.after.timespan = new Set(["lunch"]);
                    $(".time-item").each((i, v) => {
                        if ($(v).data("time") !== 'lunch') {
                            $(v).hide()
                        }
                    })
                }

                //余额相关
                userAmount = result.rfye
                //日期相关
                const dateObj = extractDatesByMonth(result.orderDate)
                orderDate = dateObj.thisMonth
                nextOrderDate = dateObj.nextMonth

                if (dateObj.nextMonth.length == 0 || result.nextMonthCount > 0) {
                    $("#nextMonth").hide()

                }

                if (result.nextMonthCount == 0) {
                    $("#nextMonth").show()
                    renderNextCalendar()
                }

                if (dateObj.thisMonth.length == 0 || result.orderSwitch == 0 || result.thisMonthCount > 0) {
                    $("#thisMonth").hide()
                } else {
                    const isHaveAfterDate = dateObj.thisMonth.some(v => new Date() < new Date(v))
                    if (!isHaveAfterDate) {
                        $("#thisMonth").hide()
                        $(".moneyInfo").hide()
                        $(".success").show()
                    } else {
                        $("#thisMonth").show()
                        renderCalendar()
                    }

                }
                if (result.nextMonthCount > 0) {
                    $("#nextMonth").hide()
                }
                if (result.nextMonthCount > 0 && result.nextMonth > 0) {
                    $(".moneyInfo").hide()
                    $(".success").show()
                }
                //金额
                timeMoney.breakfast = result.breakfastAmount
                timeMoney.lunch = result.lunchAmount
                timeMoney.dinner = result.dinnerAmount
                //timeMoney.breakfast = 0.1
                //timeMoney.lunch = 0.2
                //timeMoney.dinner = 0.3
                $("#breakfast").text(`早餐：￥${timeMoney.breakfast}/餐`)
                $("#lunch").text(`中餐：￥${timeMoney.lunch}/餐`)
                $("#dinner").text(`晚餐：￥${timeMoney.dinner}/餐`)
                $(".breakfast-amount").text(`￥${timeMoney.breakfast}/餐`)
                $(".lunch-amount").text(`￥${timeMoney.lunch}/餐`)
                $(".dinner-amount").text(`￥${timeMoney.dinner}/餐`)
                $("#nowMonthLanel").text(`${new Date().getFullYear()}年${new Date().getMonth() + 1}月`)
                $("#nextMonthLanel").text(`${new Date().getFullYear()}年${new Date().getMonth() + 2}月`)
                //默认
                //本月
                selData.now.days = $(".date-item-notDisabled").length
                selData.now.money = [...selData.now.timespan].reduce((acc, cur) => {
                    const cents = Math.round(timeMoney[cur] * 100);
                    const days = Math.round(selData.now.days * 100);
                    return acc + (cents * days) / 10000
                }, 0)
                selData.now.money = Math.round(selData.now.money * 100) / 100
                $("#nowMonthLength").text(selData.now.days)
                $("#nowMoney").text(selData.now.money)
                $(".date-item-notDisabled").first().addClass("date-item-active")
                //下月
                $("#nextMonthLength").text(selData.after.days)
                selData.after.days = nextOrderDate.length
                selData.after.money = [...selData.after.timespan].reduce((acc, cur) => {
                    const cents = Math.round(timeMoney[cur] * 100);
                    const days = Math.round(selData.after.days * 100);
                    return acc + (cents * days) / 10000
                }, 0)
                selData.after.money = Math.round(selData.after.money * 100) / 100
                $("#afterMoney").text(selData.after.money)
                $("#afterMonthLength").text(selData.after.days)
                //注册事件
                $(".date-item-notDisabled").click(function (e) {
                    $(".date-item-notDisabled").removeClass("date-item-active")
                    $(this).addClass("date-item-active")
                    const index = orderDate.indexOf(e.target.dataset.time)
                    selData.now.selDateList = orderDate.slice(index)
                    console.log("日期", selData.now.selDateList)
                    selData.now.days = selData.now.selDateList.length
                    selData.now.money = [...selData.now.timespan].reduce((acc, cur) => {
                        const cents = Math.round(timeMoney[cur] * 100);
                        const days = Math.round(selData.now.days * 100);
                        return acc + (cents * days) / 10000
                    }, 0)
                    selData.now.money = Math.round(selData.now.money * 100) / 100
                   
                    $("#nowMoney").text(selData.now.money)
                    $("#nowMonthLength").text(selData.now.days)
                })



                console.log(dateObj)
            })

        }
        //提交订单
        function submit(data) {
            showMask()
            $.post("/OrderMealManageSubSystem/OrderParameterSetting.ashx", {
                functionName: "SetOrderParameterSetting",
                data: JSON.stringify(data)
            }).then(res => {
                setTimeout(() => {
                    hideMask()
                    mui.confirm(`预定成功`, "提示", ["确认"], function (e) {
                        //getSetting()
                        location.reload()
})
                    console.log("支付订单", res)
                }, 1500)

            })
        }

        function extractDatesByMonth(dateArray) {
            const currentDate = new Date();
            const currentYear = currentDate.getFullYear();
            const currentMonth = currentDate.getMonth();

            const thisMonthDates = [];
            const nextMonthDates = [];

            dateArray.forEach(dateStr => {
                const [year, monthStr, dayStr] = dateStr.split('-');
                const yearNum = parseInt(year, 10);
                const monthNum = parseInt(monthStr, 10) - 1;
                const dayNum = parseInt(dayStr, 10);

                if (yearNum === currentYear && monthNum === currentMonth) {
                    thisMonthDates.push(dateStr);
                } else if (yearNum === currentYear && monthNum === currentMonth + 1) {
                    nextMonthDates.push(dateStr);
                } else if (yearNum === currentYear + 1 && currentMonth === 11 && monthNum === 0) {
                    nextMonthDates.push(dateStr);
                }
            });

            return {
                thisMonth: thisMonthDates,
                nextMonth: nextMonthDates
            };
        }
        $(function () {
            getSetting()

            console.log($(".date-item-notDisabled").length)
        })
    </script>
</body>
</html>